//
//  CartoonDownLoadViewController.m
//  Cartoon
//
//  Created by dllo on 15/11/4.
//  Copyright © 2015年 YSZ. All rights reserved.
//

#import "CartoonDownLoadViewController.h"
#import "CartoonDetailsCollectionViewCell.h"
#import "CartoonMyDownLoadViewController.h"
#import "CartoonMyDownLoadDetailsViewController.h"
#import "CartoonALLMyDownLoad.h"

@interface CartoonDownLoadViewController ()
@property (nonatomic, strong) UIScrollView *scrollerView;
@property (nonatomic, strong) UIButton *upDownButton;
@property (nonatomic, strong) UILabel *myLabel;
@property (nonatomic, strong) UIButton *downLoadButton;
@property (nonatomic, strong) UIButton *changeButton;
@property (nonatomic, strong) UIColor *color;
@property (nonatomic, assign) NSInteger number;
@property (nonatomic, assign) NSInteger scrollerHeight;

@property (nonatomic, strong) NSMutableArray *pageArray;

@property (nonatomic, strong) NSMutableArray *downLoadArray;
@end

@implementation CartoonDownLoadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self handler];
}
- (void)handler
{
    self.color = [UIColor whiteColor];
    self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(-1, 64, SelfViewWidth + 2, 40)];
    self.number = 0;
    self.pageArray = [NSMutableArray array];
    _myLabel.text = @"    您已选0集";
    _myLabel.layer.borderWidth = 1;
    [self.view addSubview:_myLabel];
    
    
    self.downLoadArray = [NSMutableArray array];
    BOOL isOpen = [[FMDB shareFMDB].db open];
    if (!isOpen) {
        NSLog(@"打开失败");
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonMyDownLoad (name text , image text , cartoonID text primary key , cartoonPage text)"]];
        NSLog(@"创建是否成功 : %d",creatResult);
        
    }
    
    
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM CartoonMyDownLoad"];
    
    
    while ([set next]) {
        
        CartoonMyDownLoad *myDown = [[CartoonMyDownLoad alloc]init];
        myDown.name = [set stringForColumn:@"name"];
        myDown.image = [set stringForColumn:@"image"];
        myDown.cartoonID = [set stringForColumn:@"cartoonID"];
        myDown.cartoonPage = [set stringForColumn:@"cartoonPage"];
        if ([[[myDown.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:self.model.comic_id]) {
            
            [self.downLoadArray addObject:myDown];
        }
        
    }
    
    
    
    
    
    self.scrollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64 + 40, SelfViewWidth, SelfViewHeight - 64 - 40 - 49 - 49)];
    for (NSInteger i = 0; i < [_model.lated_seqno integerValue]; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        if (i % 3 == 0) {
            button.frame = CGRectMake(10, 50 * (i / 3 + 1), SelfViewWidth / 3 - 20, 40);
            
        }else if (i % 3 == 1){
            button.frame = CGRectMake(SelfViewWidth / 3 - 20 + 10 + 20, 50 * (i / 3 + 1), SelfViewWidth / 3 - 20, 40);
        }else{
            button.frame = CGRectMake((SelfViewWidth / 3 - 20) * 2 + 10 + 20 + 20, 50 * (i / 3 + 1), SelfViewWidth / 3 - 20, 40);
        }
        for (CartoonMyDownLoad *down in self.downLoadArray) {
            if ([down.cartoonPage isEqualToString:[NSString stringWithFormat:@"%ld",i + 1]]) {
                button.userInteractionEnabled = NO;
                button.backgroundColor = [UIColor grayColor];
            }
        }
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        self.scrollerHeight = button.frame.origin.y + 40 + 20;
        button.tag = 1000 + i + 1;
        [button setTitle:[NSString stringWithFormat:@"%ld",i + 1] forState:UIControlStateNormal];
        button.titleLabel.text = [NSString stringWithFormat:@"%ld",i + 1];
        button.layer.borderWidth = 1;
        [_scrollerView addSubview:button];
    }
    
    [self.view addSubview:_scrollerView];
    
    _scrollerView.contentSize = CGSizeMake(0, self.scrollerHeight);
    
    
    
    
    self.upDownButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _upDownButton.frame = CGRectMake(SelfViewWidth - 100, 15, 80, 20);
    _upDownButton.titleLabel.text = @"倒序";
    [_upDownButton setTitle:@"倒序" forState:UIControlStateNormal];
    _upDownButton.titleLabel.font = [UIFont systemFontOfSize:18];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    imageView.image = [UIImage imageNamed:@"jiantou"];
    [_upDownButton addSubview:imageView];
    _upDownButton.tag = 1000;
    imageView.tag = 1001;
    [_upDownButton addTarget:self action:@selector(upDownButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollerView addSubview:_upDownButton];
    
    self.downLoadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _downLoadButton.frame = CGRectMake(0, SelfViewHeight - 49 - 49, SelfViewWidth / 2, 49);
    [_downLoadButton setTitle:@"全选" forState:UIControlStateNormal];
    _downLoadButton.titleLabel.text = @"全选";
    _downLoadButton.layer.borderWidth = 0.5;
    _downLoadButton.layer.borderColor = [[UIColor grayColor] CGColor];
    [_downLoadButton addTarget:self action:@selector(myDownLoadButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_downLoadButton];
    
    
    self.changeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _changeButton.frame = CGRectMake(SelfViewWidth / 2, SelfViewHeight - 49 - 49, SelfViewWidth / 2, 49);
    [_changeButton setTitle:@"下载所选" forState:UIControlStateNormal];
    _changeButton.layer.borderWidth = 0.5;
    _changeButton.tintColor = [UIColor grayColor];
    _changeButton.userInteractionEnabled = NO;
    _changeButton.layer.borderColor = [[UIColor grayColor] CGColor];
    [_changeButton addTarget:self action:@selector(myChangeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_changeButton];

}
- (void)myDownLoadButtonAction:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"全选"]) {
        _number = 0;
        for (id btn in _scrollerView.subviews) {
            if ([btn isKindOfClass:[UIButton class]] && btn != self.upDownButton) {
                UIButton *myButton = (UIButton *)btn;
                if (myButton.backgroundColor == nil) {
                   myButton.backgroundColor = [UIColor colorWithRed:50 / 255.0 green:205 / 255.0 blue:50 / 255.0 alpha:1];
                    _number++;
                }
                
            }
        }
        
        self.myLabel.text = [NSString stringWithFormat:@"    您已选%ld集",_number];
        btn.titleLabel.text = @"取消全选";
        [btn setTitle: @"取消全选" forState:UIControlStateNormal];
        
    }else{
        for (id btn in _scrollerView.subviews) {
            if ([btn isKindOfClass:[UIButton class]] && btn != self.upDownButton) {
                UIButton *myButton = (UIButton *)btn;
                if ([myButton.backgroundColor isEqual:[UIColor colorWithRed:50 / 255.0 green:205 / 255.0 blue:50 / 255.0 alpha:1]]) {
                    myButton.backgroundColor = nil;
                }
                
            }
        }
        _number = 0;
        self.myLabel.text = [NSString stringWithFormat:@"    您已选%ld集",_number];
        btn.titleLabel.text = @"全选";
        self.color = [UIColor whiteColor];
        [btn setTitle: @"全选" forState:UIControlStateNormal];
    }
    
    if ([self.myLabel.text isEqualToString:@"    您已选0集"]) {
        self.changeButton.userInteractionEnabled = NO;
        self.changeButton.tintColor = [UIColor grayColor];
        [self.pageArray removeAllObjects];
    }else{
        self.changeButton.userInteractionEnabled = YES;
        self.changeButton.tintColor = nil;
        for (NSInteger i = 0; i < [_model.lated_seqno integerValue]; i++) {
            [self.pageArray addObject:[NSString stringWithFormat:@"%ld",i]];
        }
    }
}
- (void)myChangeButtonAction:(UIButton *)btn
{
//    CartoonMyDownLoadViewController *myDown = [[CartoonMyDownLoadViewController alloc] init];
//    myDown.myImage = self.myImage;
//    myDown.name = self.name;
//    myDown.myImageUrl = self.myImageUrl;
//    myDown.pageArray = self.pageArray;
//    CartoonDetailsModel *model = [self.dataArr objectAtIndex:0];
//    myDown.comic_id = model.comic_id;
//    [self.navigationController pushViewController:myDown animated:YES];
    

    CartoonMyDownLoadDetailsViewController *myDown = [[CartoonMyDownLoadDetailsViewController alloc] init];
    myDown.myImageUrl = self.myImageUrl;
    myDown.pageArray = self.pageArray;
    CartoonDetailsModel *model = [self.dataArr objectAtIndex:0];
    myDown.comic_id = model.comic_id;
    myDown.name = self.name;
    
    
    BOOL isOpen = [[FMDB shareFMDB].db open];
    if (!isOpen) {
        NSLog(@"打开失败");
    }else{
        
        BOOL creatResult1 = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonALLMyDownLoad (name text , image text , cartoonID text primary key)"]];
        NSLog(@"creatResult1 = 创建是否成功 : %d",creatResult1);
    }
    
    
    BOOL insertResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"insert into CartoonALLMyDownLoad values ('%@','%@','%@')",self.name,self.myImageUrl,model.comic_id]];
    
    if (insertResult == YES) {
        NSLog(@"creatResult1插入成功");
    }else{
        NSLog(@"插入失败");
    }
    
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM CartoonALLMyDownLoad"];
    
    while ([set next]) {
        CartoonALLMyDownLoad *myALLDown = [[CartoonALLMyDownLoad alloc]init];
        myALLDown.name = [set stringForColumn:@"name"];
        myALLDown.image = [set stringForColumn:@"image"];
        myALLDown.cartoonID = [set stringForColumn:@"cartoonID"];
        
    }
    
    
    [self.navigationController pushViewController:myDown animated:YES];
    
    
}
- (void)upDownButtonAction:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"倒序"]) {
        btn.titleLabel.text = @"正序";
        [btn setTitle:@"正序" forState:UIControlStateNormal];
        [btn viewWithTag:1001].transform = CGAffineTransformMakeRotation(M_PI);

        
    }else{
        btn.titleLabel.text = @"倒序";
        [btn setTitle:@"倒序" forState:UIControlStateNormal];
        [btn viewWithTag:1001].transform = CGAffineTransformMakeRotation(0);
      
    }
    NSMutableArray *array = [NSMutableArray array];
    NSMutableArray *nildown = [NSMutableArray array];
    for (id btn in _scrollerView.subviews) {
        if ([btn isKindOfClass:[UIButton class]] && btn != self.upDownButton) {
            UIButton *myButton = (UIButton *)btn;
            if ([myButton.backgroundColor isEqual:[UIColor colorWithRed:50 / 255.0 green:205 / 255.0 blue:50 / 255.0 alpha:1]]) {
                [array addObject:[NSString stringWithFormat:@"%ld",myButton.tag]];
                myButton.backgroundColor = nil;
            }
            if ([myButton.backgroundColor isEqual:[UIColor grayColor]]) {
                [nildown addObject:[NSString stringWithFormat:@"%ld",myButton.tag]];
                myButton.backgroundColor = nil;
            }
            [myButton setTitle:[NSString stringWithFormat:@"%ld",[_model.lated_seqno integerValue] - [myButton.titleLabel.text integerValue] + 1] forState:UIControlStateNormal];
            myButton.tag = [_model.lated_seqno integerValue] - [myButton.titleLabel.text integerValue] + 1 + 1000;
            myButton.userInteractionEnabled = YES;
            
        }
    }
    for (NSString *str in array) {
        [_scrollerView viewWithTag:[str integerValue]].backgroundColor = [UIColor colorWithRed:50 / 255.0 green:205 / 255.0 blue:50 / 255.0 alpha:1];
    }
    for (NSString *str in nildown) {
        [_scrollerView viewWithTag:[str integerValue]].backgroundColor = [UIColor grayColor];
        [_scrollerView viewWithTag:[str integerValue]].userInteractionEnabled = NO;
    }
}


- (void)buttonAction:(UIButton *)btn
{
    
    if (btn.backgroundColor == nil) {
        btn.backgroundColor = [UIColor colorWithRed:50 / 255.0 green:205 / 255.0 blue:50 / 255.0 alpha:1];
        _number ++;
        [self.pageArray addObject:[NSString stringWithFormat:@"%ld",btn.tag - 1000 - 1]];
    }else{
        _number --;
        btn.backgroundColor = nil;
       [self.pageArray removeObject:[NSString stringWithFormat:@"%ld",btn.tag - 1000 - 1]];
    }
    
    self.myLabel.text = [NSString stringWithFormat:@"    您已选%ld集",_number];
    if ([self.myLabel.text isEqualToString:@"    您已选0集"]) {
        self.changeButton.userInteractionEnabled = NO;
        self.changeButton.tintColor = [UIColor grayColor];
    }else{
        self.changeButton.userInteractionEnabled = YES;
        self.changeButton.tintColor = nil;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    self.downLoadArray = [NSMutableArray array];
    BOOL isOpen = [[FMDB shareFMDB].db open];
    if (!isOpen) {
        NSLog(@"打开失败");
    }else{
        
        BOOL creatResult = [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"create table CartoonMyDownLoad (name text , image text , cartoonID text primary key , cartoonPage text)"]];
        NSLog(@"创建是否成功 : %d",creatResult);
        
    }
    
    
    FMResultSet *set = [[FMDB shareFMDB].db executeQuery:@"SELECT * FROM CartoonMyDownLoad"];
    
    
    while ([set next]) {
        
        CartoonMyDownLoad *myDown = [[CartoonMyDownLoad alloc]init];
        myDown.name = [set stringForColumn:@"name"];
        myDown.image = [set stringForColumn:@"image"];
        myDown.cartoonID = [set stringForColumn:@"cartoonID"];
        myDown.cartoonPage = [set stringForColumn:@"cartoonPage"];
        if ([[[myDown.cartoonID componentsSeparatedByString:@"/"] lastObject] isEqualToString:self.model.comic_id]) {
            
            [self.downLoadArray addObject:myDown];
        }
        
    }
    for (NSInteger i = 0; i < [_model.lated_seqno integerValue]; i ++) {
        [[self.view viewWithTag:1000 + i + 1] removeFromSuperview];
        
    }
    for (NSInteger i = 0; i < [_model.lated_seqno integerValue]; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        if (i % 3 == 0) {
            button.frame = CGRectMake(10, 50 * (i / 3 + 1), SelfViewWidth / 3 - 20, 40);
            
        }else if (i % 3 == 1){
            button.frame = CGRectMake(SelfViewWidth / 3 - 20 + 10 + 20, 50 * (i / 3 + 1), SelfViewWidth / 3 - 20, 40);
        }else{
            button.frame = CGRectMake((SelfViewWidth / 3 - 20) * 2 + 10 + 20 + 20, 50 * (i / 3 + 1), SelfViewWidth / 3 - 20, 40);
        }
        for (CartoonMyDownLoad *down in self.downLoadArray) {
            if ([down.cartoonPage isEqualToString:[NSString stringWithFormat:@"%ld",i + 1]]) {
                button.userInteractionEnabled = NO;
                button.backgroundColor = [UIColor grayColor];
            }
        }
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        self.scrollerHeight = button.frame.origin.y + 40 + 20;
        button.tag = 1000 + i + 1;
        [button setTitle:[NSString stringWithFormat:@"%ld",i + 1] forState:UIControlStateNormal];
        button.titleLabel.text = [NSString stringWithFormat:@"%ld",i + 1];
        button.layer.borderWidth = 1;
        [_scrollerView addSubview:button];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
